﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using MySql.Data.MySqlClient;
using Services.Common;
using BartonExtension;
using SQLWrapper;
using Model.App;
using Model.Images;
using Model.Weixin;
using Model;

namespace Services.User
{
    public class ISMBlacklistServiceProvider : ISMServiceProvider
    {
        public const string GET_BLACK_LIST = "get_black_list";
        public const string REMOVE_FROM_BLACKLIST = "remove_from_black_list";
        public const string ADD_TO_BLACKLIST = "add_to_blacklist";
        public override Task<ISMServiceResult> doProcess(ISMServiceModel model)
        {
            if(model.operationIdentifier.Equals(GET_BLACK_LIST))
            {
                Dictionary<string, object> param = model.GetState<Dictionary<string, object>>();
                UInt64 uid = param["uid"].toUInt64().Value;
                string token = param["token"].ToString();
                return GetBlacklist(uid, token);
            }
            else if(model.operationIdentifier.Equals(REMOVE_FROM_BLACKLIST))
            {
                ISMBlockUserRequest request = model.GetState<ISMBlockUserRequest>();
                return UnblockUser(request);
            }
            else if(model.operationIdentifier.Equals(ADD_TO_BLACKLIST))
            {
                ISMBlockUserRequest request = model.GetState<ISMBlockUserRequest>();
                return BlockUser(request);
            }
            return base.defaultProcess();
        }

        private Task<ISMServiceResult> GetBlacklist(UInt64 uid,string token)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                        {
                            cmd.CommandText = "proc_client_get_blacklist";
                            cmd.Parameters.Add("_uid", uid, ParameterDirection.Input);
                            cmd.Parameters.Add("_token", token, ParameterDirection.Input);
                        },
                        e =>
                        {
                            if (e != null)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = e;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            }
                        },
                        data =>
                        {
                            if(data.Count == 1 && data.First().ContainsKey("error"))
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                                result.errorMsg = "Token 验证非法";
                            }
                            else
                            {
                                List<ISMBlockPerson> blocks = new List<ISMBlockPerson>();
                                data.ForEach(d =>
                                    {
                                        ISMBlockPerson person = new ISMBlockPerson();
                                        person.ID = d["ID"].toUInt64().Value;
                                        person.block_id = d["block_id"].toUInt64().Value;
                                        person.wechat_name = d["wechatname"].ToString();
                                        person.username = d["username"].ToString();
                                        person.headimgurl = d["headimgUrl"].ToString();
                                        blocks.Add(person);
                                    });
                                result.dbReturningState = blocks;
                            }
                        }, CommandType.StoredProcedure, false);
                    return result;
                });
        }
        private Task<ISMServiceResult> BlockUser(ISMBlockUserRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperation(cmd =>
                        {
                            cmd.CommandText = "proc_client_block_user";
                            cmd.Parameters.Add("?_owner", request.owner, ParameterDirection.Input);
                            cmd.Parameters.Add("?_blockid", request.blockid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                            cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                            cmd.ExecuteNonQuery();
                            int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                            if (errorcode == -1)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = "Token 验证失败";
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                            }
                            else if(errorcode == -2)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = "用户不存在";
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_USER_NOT_EXISTS;
                            }
                            else if (errorcode == -3)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = "无法将该用户加入黑名单，可能该用户已存在于您的黑名单中";
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_USER_IS_ALREADY_BLOCKED;
                            }
                            else if (errorcode == -4)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = "内部错误";
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_UNKNOWN_ERR;
                            }
                        },
                        e =>
                        {
                            if(e != null)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = e;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            }
                        }, CommandType.StoredProcedure, false);
                    return result;
                });
        }
        private Task<ISMServiceResult> UnblockUser(ISMBlockUserRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperation(cmd =>
                        {
                            cmd.CommandText = "proc_client_unblock_user";
                            cmd.Parameters.Add("?_owner", request.owner, ParameterDirection.Input);
                            cmd.Parameters.Add("?_blockid", request.blockid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                            cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                            cmd.ExecuteNonQuery();
                            int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                            if(errorcode == -1)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = "Token 验证失败";
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                            }
                        },
                        e =>
                        {
                            if(e != null)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                                result.errorMsg = e;
                            }
                        }, CommandType.StoredProcedure, false);
                    return result;
                });
        }
    }
}
